package org.turman.buobaobook.controller;

import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.turman.buobaobook.model.ResponseBean;
import org.turman.buobaobook.model.entity.Book;
import org.turman.buobaobook.model.entity.BookSource;
import org.turman.buobaobook.model.request.AddBookBean;
import org.turman.buobaobook.model.request.QueryBookBean;
import org.turman.buobaobook.service.BookService;
import org.turman.buobaobook.service.BookSourceService;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/book")
@Tag(name = "书籍管理接口", description = "书籍管理功能模块所有接口")
public class BookController {
    @Autowired
    private BookService bookService;
    @Autowired
    private BookSourceService bookSourceService;

    @ApiResponse(responseCode = "200", description = "成功响应", content = @Content(schema = @Schema(implementation = String.class)))
    @Operation(summary = "书籍详情",description = "根据书籍id获取书籍详情")
    @GetMapping("/{id}")
    public ResponseBean<Book> getBook(@PathVariable Long id) {
        Book book = bookService.selectById(id);
        if (book == null) {
            return ResponseBean.fail("书籍不存在");
        }
        return ResponseBean.success(book);
    }

    //    @ApiOperation("书籍列表")
    @PostMapping("/list")
    public ResponseBean<PageInfo<Book>> getBookList(@RequestBody QueryBookBean queryBookBean) {
        PageInfo<Book> bookPageInfo = bookService.selectList(queryBookBean);
        return ResponseBean.success(bookPageInfo);
    }

    //    @ApiOperation("新增书籍")
    @PostMapping("/add")
    public ResponseBean addBook(@RequestBody AddBookBean addBookBean) {
        try {

        } catch (Exception e) {
            return ResponseBean.fail(e.getMessage());
        }
        Book book = new Book();
        book.setBookName(addBookBean.getTitle());
        book.setBookCover(addBookBean.getCover());
        book.setBookAuthor(addBookBean.getAuthor());
        book.setWebSource(addBookBean.getSource());
        book.setBookContent(addBookBean.getContent());
        List<BookSource> bookSources = new ArrayList<>();
        if (addBookBean.getUrls() != null && addBookBean.getUrls().size() > 0) {
            for (int i = 0; i < addBookBean.getUrls().size(); i++) {
                BookSource bookSource = new BookSource(addBookBean.getUrls().get(i), addBookBean.getFiles().get(i));
                bookSources.add(bookSource);
            }
        }
        bookService.insert(book, bookSources);
        return ResponseBean.success();
    }

    /**
     * 直接通过文件路径下载文件（本地文件系统）
     *
     * @param sourceId
     * @return
     */
//    @ApiOperation("书籍资源下载")
    @GetMapping("/download/{sourceId}")
    public ResponseEntity<FileSystemResource> downloadFile(@PathVariable Long sourceId) {
        BookSource bookSource = bookSourceService.selectById(sourceId);
        FileSystemResource fileSystemResource = new FileSystemResource(bookSource.getLocalPath());

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileSystemResource.getFilename());

        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(fileSystemResource);
    }


    @Value("${upload.path}") // 应用配置中定义的上传路径
    private String uploadPath;

    //    @ApiOperation("数据上传")
    @GetMapping("/upload")
    public ResponseBean handleFileUpload(@RequestParam("imageFile") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                // 生成唯一的文件名以避免冲突
                String uniqueFileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
                // 指定保存文件的路径
                Path filePath = Paths.get(uploadPath, uniqueFileName);
                // 保存文件到服务器
                Files.copy(file.getInputStream(), filePath);
                return ResponseBean.success();
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseBean.fail(e.getMessage());
            }
        } else {
            return ResponseBean.fail("文件为空");
        }
    }

    @PostMapping("/pagelist")
    public ResponseBean getBookListByPage(@RequestBody QueryBookBean queryBookBean){
        PageInfo<Book> bookPageInfo = bookService.selectList(queryBookBean);
        return ResponseBean.success(bookPageInfo);
    }

//    @GetMapping("/download2/{sourceId}")
//    public ResponseEntity<FileSystemResource> downloadFile2(@PathVariable Long sourceId) {
//        InputStreamResource resource = getFileFromDatabase(sourceId);
//        String filename = "downloadedFile." + getFileExtension(sourceId); // 根据实际情况获取文件扩展名
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
//
//        return ResponseEntity.ok()
//                .headers(headers)
//                .contentType(MediaType.APPLICATION_OCTET_STREAM)
//                .body(resource);
//    }
}





























